<?php
namespace modules\auth;
use \firebase\jwt;
use \phiction\exceptions\bad_request;

class security
{
    const RANDOM_ID_LENGTH = 2 * self::_RANDOM_BYTES_LENGTH;
    const _RANDOM_BYTES_LENGTH = 32;

    public static function random_id()
    {
        return bin2hex(random_bytes(self::_RANDOM_BYTES_LENGTH));
    }


    public static function make_credential(string $password): string
    {
        if (strlen($password) > 64) throw new bad_request("password too long, cannot exceed 64 bytes");
        return password_hash($password, PASSWORD_BCRYPT);
    }

    public static function verify_password(string $password, string $credential): bool
    {
        if (strlen($password) > 64) throw new bad_request("password too long, cannot exceed 64 bytes");
        return password_verify($password, $credential);
    }


    public static function make_token(array $shards): string
    {
        $now = time();

        $shards['exp']     = $now + 3 * 24*60*60;   // 3 days
        $shards['refresh'] = $now + 5 * 60;         // 5 minutes
        // exp     -> expired-after: token is invalid after this time
        // refresh -> refresh-after: token will be checked against the database after this time,
        //                           and a new token will be re-issued

        return jwt::encode($shards, self::key());
    }

    public static function break_token(string $token): array
    {
        return (array)jwt::decode($token, self::key(), ['HS256']);
    }


    private static function key(): string
    {
        return "b.cjprods.org";
    }
}

